package top.kaoshanji.ch04;

import com.google.common.io.Resources;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;
import java.util.Scanner;

/**
 * 代码清单 ch04-06：URLConnection示例(4.3.3节、提交数据)
 * author kaoshanji
 * ^_^
 * create time 2024/12/8 10:37
 */
public class PostTest {

    private static final Logger logger = LogManager.getLogger(PostTest.class);

    static final String FILE_NAME = "ch04/post/post.properties";

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 ch04-06：URLConnection示例(4.3.3节、提交数据)...");

        URL urlFile = Resources.getResource(FILE_NAME);
        var props = new Properties();
        props.load(urlFile.openStream());

        String urlString = props.remove("url").toString();
        Object userAgent = props.remove("User-Agent");
        Object redirects = props.remove("redirects");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        String result = doPost(new URL(urlString), props,
                userAgent == null ? null : userAgent.toString(),
                redirects == null ? -1 : Integer.parseInt(redirects.toString()));

        System.out.println(result);

    }

    public static String doPost(URL url, Map<Object, Object> nameValuePairs, String userAgent, int redirects)
            throws IOException {

        var connection = (HttpURLConnection)url.openConnection();
        if (userAgent != null) {
            connection.setRequestProperty("User-Agent", userAgent);
        }

        if (redirects >= 0) {
            // 关闭重定向
            connection.setInstanceFollowRedirects(false);
        }

        // 设置提交数据...也就有了输出流
        connection.setDoOutput(true);

        try (var out = new PrintWriter(connection.getOutputStream())) {
            var first = true;
            for (Map.Entry<Object, Object> pair: nameValuePairs.entrySet()) {
                if (first) {
                    first = false;
                } else {
                    out.print('&');
                }
                String name = pair.getKey().toString();
                String value = pair.getValue().toString();

                out.print(name);
                out.print('=');
                out.print(URLEncoder.encode(value, StandardCharsets.UTF_8));
            }
        }


        String encoding = connection.getContentEncoding();
        if (encoding == null) {
            encoding = "UTF-8";
        }

        var response = new StringBuilder();
        try (var in = new Scanner(connection.getInputStream(), encoding)) {
            while (in.hasNextLine()) {
                response.append(in.nextLine());
                response.append("\n");
            }
        }

        return response.toString();
    }


}
